package resp

import (
	"net/http"

	"github.com/zeromicro/go-zero/rest/httpx"
	"yookie.me/pdfreader/pkg/errx"
)

const (
	BusinessOK     = 0
	BusinessErr    = 1
	BusinessErrMsg = "failed"
	BusinessOkMsg  = "ok"
)

type BaseResponse[T any] struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    T      `json:"data,omitempty"`
}

func Json(w http.ResponseWriter, v any) {
	httpx.OkJson(w, wrapResponse)
}

func wrapResponse(v any) BaseResponse[any] {
	var res BaseResponse[any]
	switch data := v.(type) {
	case *errx.CodeMsg:
		res.Code = data.Code
		res.Message = data.Msg
	case error:
		res.Code = BusinessErr
		res.Message = data.Error()
	default:
		res.Code = BusinessOK
		res.Message = BusinessOkMsg
	}
	return res
}
